using System;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
using Avalonia.Threading;
using EasoScreen.Plugins;

namespace EasoScreen.Plugins;

public partial class Scheduler : UserControl
{
    TaskTemplate taskTemplate = new TaskTemplate();
    XmlEditor xmlEditor = new XmlEditor();
    public Scheduler()
    {
        InitializeComponent();



        DispatcherTimer timer = new DispatcherTimer();
        timer.Tick += Timer_Tick;
        timer.IsEnabled = true;
    }

    private void Timer_Tick(object? sender, EventArgs e)
    {
        try
        {
            taskTemplate = xmlEditor.GetLatestTask();
            xmlEditor.SortTasksByDate(); //sort the tasks by date in the XML file
        }
        catch (NullReferenceException)
        {
            TaskName.Text = "没有任务待处理。";
            TaskDueTime.Text = "";
            return;
        }
        TaskName.Text = taskTemplate.Name;
        TaskDueTime.Text = taskTemplate.Time;
        DateTime currentDateTime = DateTime.Now;
        string dueDateAndTime = $"{taskTemplate.Date}/{taskTemplate.Time.Substring(taskTemplate.Time.IndexOf("-") + 1)}";
        DateTime dueDateTime = DateTime.ParseExact(dueDateAndTime, "yyyy/MM/dd/HH:mm", null);
        if (dueDateTime <= currentDateTime)
        {
            xmlEditor.DeleteLatestTask();//delete the task from the XML file
        }
        
    }
}